package com.fgba.express.security;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fgba.express.comm.result.IResultCode;
import com.fgba.express.comm.result.Result;
import com.fgba.express.comm.result.ResultCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author fgba
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        Result<Object> result;
        if (e instanceof JwtAuthenticationException) {
            IResultCode resultCode = ((JwtAuthenticationException) e).getResultCode();
            if (resultCode == null) {
                result = Result.error(((JwtAuthenticationException) e).getCode().toString(), ((JwtAuthenticationException) e).getMessage(), null);
            } else {
                result = Result.error(resultCode.getCode(), resultCode.getMsg(), null);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            result = Result.error(ResultCode.USER_NOT_LOGIN.getCode(), ResultCode.USER_NOT_LOGIN.getMsg(), null);
        }
        outputStream.write(new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
